package com.thinkit.directive.components;

import com.thinkit.core.constant.Channel;
import com.thinkit.utils.model.ApiResult;
import com.thinkit.utils.utils.Checker;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * 模板静态化组件
 */
@Slf4j
@Component
public class TemplateComponent {
    /**
     * 创建页面
     * @return
     */
    public ApiResult createStaticFile(String tempPath, String destPath, Map<String, Object> param, Configuration configuration) {
        try {
            FileOutputStream outputStream = new FileOutputStream(initDir(destPath));
            Template t = configuration.getTemplate(tempPath);
            Writer out = new OutputStreamWriter(outputStream,Charset.forName("UTF-8"));
            t.process(param, out);
            format(param,100,destPath);
            return ApiResult.result(param);
        } catch (IOException|TemplateException e) {
            log.error(e.getMessage());
            format(param,0,destPath);
            return ApiResult.result(param,20006);
        }
    }

    private void format(Map<String, Object> param,int percent,String destPath){
        param.put(Channel.PERCENT,percent);
        param.put(Channel.DEST_PATH,destPath);
    }

    private File initDir(String destPath){
        File destFile = new File(destPath);
        if (!destFile.exists()) {
            File pfile = destFile.getParentFile();
            if(Checker.BeNotNull(pfile)){
                pfile.mkdirs();
            }
        }
        return destFile;
    }
}
